package com.os.osframe.scaffold.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.os.osframe.scaffold.create.AutoCreateCodeFactory;
import com.os.osframe.scaffold.domain.AutoConfigModule;
import com.os.osframe.scaffold.domain.ScaffoldXmlField;
import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.service.IConfigModuleService;
import com.os.osframe.scaffold.service.IConfigTableService;
import com.os.osframe.scaffold.util.FileToZipUtil;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import com.os.osframe.util.JSONHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchun on 16/7/4.
 */
@Controller
@RequestMapping("/config")
public class AutoConfigController {
    @Resource
    IConfigModuleService configModuleService;
    @Resource
    IConfigTableService configTableService;

    @Resource
    protected PropertyConfigurerLoader propertyConfigurer;
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView defaultIndex() throws Exception {
        ModelAndView modelView = new ModelAndView();
        modelView.setViewName("redirect:/index.html");//默认直接跳转到首页
        return modelView;
    }

    /**
     * 自动配置主页
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request)throws Exception {
        return "config/index";//路径获取为通用
    }

    /**
     * 表结构设计
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/table")
    public String table(HttpServletRequest request, Model model)throws Exception {
        String module=request.getParameter("module");
        if(module!=null&& !"".equals(module.trim())){
            List<ScaffoldXmlTable> tableList=configTableService.getTableList(module);
            model.addAttribute("tableList",tableList);
        }

        return "config/table/list";
    }
    /**
     * 模块新建
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/table/add")
    public String tableAdd(HttpServletRequest request, Model model)throws Exception {
        ScaffoldXmlTable scaffoldXmlTable=new ScaffoldXmlTable();
        model.addAttribute("configTable",scaffoldXmlTable);
        return "config/table/edit";
    }
    /**
     * 模块编辑
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/table/edit")
    public String tableEdit(HttpServletRequest request, Model model)throws Exception {
        String module=request.getParameter("module");
        String tableName=request.getParameter("name");
        ScaffoldXmlTable scaffoldXmlTable=configTableService.findTableName(module,tableName);
        if(module!=null && !"".equals(module) &&  tableName!=null && !"".equals(tableName)) {
            model.addAttribute("configTable", scaffoldXmlTable);
            List fieldsList = scaffoldXmlTable.getScaffoldXmlFieldList();
            if (fieldsList != null && !fieldsList.isEmpty()) {
                JSONArray arr = (JSONArray) JSONArray.toJSON(fieldsList);
                model.addAttribute("fieldsList", arr);
            }
        }
        return "config/table/edit";
    }
    @ResponseBody
    @RequestMapping("/table/fields")
    public String fieldList(HttpServletRequest request, Model model)throws Exception {
        //获取当前表单的字段列表
        JSONObject jsonObject=new JSONObject();
        String module=request.getParameter("module");
        String tableName=request.getParameter("tableName");
        if(module!=null && !"".equals(module) &&  tableName!=null && !"".equals(tableName)){
            JSONArray arr=(JSONArray)JSONArray.toJSON(configTableService.getFieldsList(module, tableName));
            jsonObject.put("data",arr);
            jsonObject.put("error","0");
            jsonObject.put("info","");
            return jsonObject.toJSONString();
        }
        jsonObject.put("error","1");
        jsonObject.put("info","module和tableName参数未指定");
        return  jsonObject.toJSONString();
    }
    @ResponseBody
    @RequestMapping("/table/code")
    public String tableCode(HttpServletRequest request, Model model)throws Exception {
        JSONObject jsonObject=new JSONObject();
        String module=request.getParameter("module");
        if(module!=null && !"".equals(module)){
            try {
                AutoCreateCodeFactory.createCode(module);//生成代码
                Boolean bool=configTableService.moduleZip(module);//生成完成后压缩生成zip文件
                if(!bool){
                    jsonObject.put("error","1");
                    jsonObject.put("info","生成代码成功，压缩文件失败。");
                }else{
                    jsonObject.put("error","0");
                    jsonObject.put("info","");
                }

            }catch (Exception e){
                e.printStackTrace();
                jsonObject.put("error","1");
                jsonObject.put("info","生成代码失败！");
            }
        }
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("/table/down")
    public String tableDown(HttpServletRequest request, Model model,HttpServletResponse response)throws Exception {
        JSONObject jsonObject=new JSONObject();
        boolean bool=false;
        String module=request.getParameter("module");
        InputStream inputStream=null;
        OutputStream os=null;
        if(module!=null && !"".equals(module)){
            try {

                String basePath = (String) propertyConfigurer.getProperty("osframe.file.path");//获取属性配置的服务器路径
                if (basePath.substring(basePath.length() - 1).equals("/")) {
                    basePath = basePath.substring(basePath.length() - 1);
                }
                String targetPath=basePath+"/auto/downloads";
                inputStream = new FileInputStream(new File(targetPath+"/"+module+".zip"));//文件路径

                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + module+".zip");
                os = response.getOutputStream();
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
            }catch (Exception e){
                e.printStackTrace();
                jsonObject.put("error","1");
                jsonObject.put("info","生成代码失败！");
                bool=true;
            }finally {
                // 这里主要关闭。
                if(os!=null){
                    os.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            }
        }
        if(bool){
            return jsonObject.toJSONString();
        }
        return null;
    }
    /**
     * 模块编辑
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/table/look")
    public String tableLook(HttpServletRequest request, Model model)throws Exception {
        ScaffoldXmlTable scaffoldXmlTable=new ScaffoldXmlTable();
        model.addAttribute("configTable",scaffoldXmlTable);
        return "config/table/look";
    }
    /**
     * 模块保存
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/table/save")
    public String tableSave(HttpServletRequest request, Model model)throws Exception {
        JSONObject jsonObject=new JSONObject();
        String module=request.getParameter("module");
//        module="temp";
        String tableName=request.getParameter("tableName");
        String tableInfo=request.getParameter("tableInfo");
        String status=request.getParameter("status");
        if(module!=null && !"".equals(module)){
            ScaffoldXmlTable domain=new ScaffoldXmlTable();
            domain.setStatus(status);
            domain.setTableInfo(tableInfo);
            domain.setTableName(tableName);
            List jList=(List)JSONHelper.json2List(request.getParameter("scaffoldXmlFieldList"), ScaffoldXmlField.class);
            domain.setScaffoldXmlFieldList(jList);
            configTableService.saveTable(module,domain);
        }
        request.getParameterMap();
        JSONArray obj=(JSONArray)JSONArray.parse(request.getParameter("scaffoldXmlFieldList"));
        jsonObject.put("error",0);
        jsonObject.put("info","暂未实现逻辑");
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("/table/delete")
    public String tableDelete(HttpServletRequest request, Model model)throws Exception {
        JSONObject jsonObject=new JSONObject();
        String module=request.getParameter("module");
        String tableName=request.getParameter("name");
        if(module!=null && !"".equals(module) &&  tableName!=null && !"".equals(tableName)) {
            String reData=configTableService.delTable(module,tableName);
            jsonObject.put("error",reData);
            if(reData!=null && "1".equals(reData)){//失败
                jsonObject.put("info","删除失败，没有找到删除表");
            }
        }
        return jsonObject.toJSONString();
    }
    /**
     * 模块设计
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/module")
    public String module(HttpServletRequest request, Model model)throws Exception {
        //configModuleService.initLoadConfig();
        List<AutoConfigModule> configList=configModuleService.getModuleList();
        model.addAttribute("infoList",configList);//不做分页的列表展示，原则上模块不会太多，所以就全部展示出来
        return "config/module/list";
    }
    /**
     * 模块新建
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/module/add")
    public String moduleAdd(HttpServletRequest request, Model model)throws Exception {

        AutoConfigModule autoConfigModule=new AutoConfigModule();
        autoConfigModule.init();

        model.addAttribute("configModule",autoConfigModule);//不做分页的列表展示，原则上模块不会太多，所以就全部展示出来
        return "config/module/edit";
    }
    /**
     * 模块编辑
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/module/edit")
    public String moduleEdit(HttpServletRequest request, Model model)throws Exception {
        String id=request.getParameter("id");
        if(id!=null&& !"".equals(id.trim())){
            AutoConfigModule autoConfigModule=configModuleService.findModuleId(id);
            model.addAttribute("configModule",autoConfigModule);
        }

        return "config/module/edit";
    }

    /**
     * 模块查看
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/module/look")
    public String moduleLook(HttpServletRequest request, Model model)throws Exception {
        String id=request.getParameter("id");
        if(id!=null&& !"".equals(id.trim())){
            AutoConfigModule autoConfigModule=configModuleService.findModuleId(id);
            model.addAttribute("configModule",autoConfigModule);
        }

        return "config/module/look";
    }
    /**
     * 模块新建
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/module/save")
    public String moduleSave(HttpServletRequest request, Model model,AutoConfigModule domain)throws Exception {
        JSONObject jsonObject=new JSONObject();
        //TODO 解析xml保存，保存位置，配置文件中，auto/config/module.xml,
        configModuleService.saveModule(domain);

        jsonObject.put("error",0);
        jsonObject.put("info","暂未实现逻辑");
        return jsonObject.toJSONString();
    }
    @ResponseBody
    @RequestMapping("/module/delete")
    public String moduleDelete(HttpServletRequest request, Model model)throws Exception {
        JSONObject jsonObject=new JSONObject();
        String id=request.getParameter("id");
        if(id!=null&& !"".equals(id.trim())){
            configModuleService.delete(id);
        }
        jsonObject.put("error",0);
        jsonObject.put("info","暂未实现逻辑");
        return jsonObject.toJSONString();
    }
}
